package App.Model;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.List;

public class UserListCellRenderer extends DefaultListCellRenderer {
    public HashMap<String, Boolean> conformUser;//用于存放消息提示(userId)  可以保存到本地文件中,下次登录同样可以读取
    public String nowUser;//当前聊天对象(nowUser)
    private int nowClicked = -1;

    //JLst渲染器
    //list - 正在绘制的 JList,value - 由 list.getModel().getElementAt(index) 返回的值,
    // index - 单元格索引。isSelected - 如果选择了指定的单元格，则为 true。cellHasFocus - 如果指定的单元格拥有焦点，则为 true。
    @Override
    public Component getListCellRendererComponent(JList list,
                                                  Object value, int index, boolean isSelected, boolean cellHasFocus) {
        setText(value.toString());
        Color background = null;
        Color foreground = null;

        String nowUserCompare = value.toString().replace("●", "");
        if (conformUser != null) {
            for (String key : conformUser.keySet()) {
                if (nowUserCompare.equals(key)) {
                    background = Color.decode("#ADD8E6");
                    foreground = Color.WHITE;
                    break;//因为只给一个单元格着色,故可以break
                }
            }
        }
        if (nowUserCompare.equals(nowUser)) {//渲染当前聊天对象的list单元格
            background = Color.red;
            ;
            foreground = Color.WHITE;
        }
        if (index == nowClicked) {//渲染被右键展开菜单的位置的list单元格
            background = Color.white;
            foreground = Color.gray;
        }
        this.setBorder(BorderFactory.createEmptyBorder(4, 0, 4, 0)); // 设置上、右、下、左的边框间距为10像素

        setBackground(background);
        setForeground(foreground);
        return this;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.GRAY);
        g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
    }

    public void addConformUser(String userId) {//加入提醒
        if (conformUser == null) {//当conformUser不存在时,特殊处理
            conformUser = new HashMap<>();
        }
        conformUser.put(userId, true);
    }

    public void removeConformUser(String userId) {
        if (conformUser != null) {
            if (conformUser.containsKey(userId))
                conformUser.remove(userId);
        }
    }

    public void addConformUserToService(List<String> senders) {
        conformUser = new HashMap<>();//登陆时对conformUser的初始化
        for (String s : senders) {
            conformUser.put(s, true);
        }
    }

    public int getNowClicked() {
        return nowClicked;
    }

    public void setNowClicked(int nowClicked) {
        this.nowClicked = nowClicked;
    }
}
